/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import entities1.Event;
import entities1.InvitationRequest;
import entities1.Users;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;


/**
 *
 * @author takamflore
 */
@Stateless
public class EventDaoImpl implements EventDao{
    @PersistenceContext(unitName = "meteoCal_PU")
    private EntityManager em;
    @Inject 
    InvitationDao invitationDao;
    @Inject
    UserDao usersDao;
    InvitationRequest invitation;
    List<Users> result = new ArrayList();
    List<Event> events;
    Event event;
    //
    @Override
    public void addEvent(Event event) throws InvalidEventFormatException{
        em.persist(event);   
    }
    //
    @Override
    public List<Event> getAllEvent(int userId){
        events= em.createNamedQuery("Event.findAll").getResultList();
        for(Event C:events){
            if(C.getOrganizer().getId()!=userId){
              try {
            events.remove(C);
        } catch (UnsupportedOperationException uoe) {
            //events = new ArrayList<Event>(events);
            events.remove(C);
        }
     }
     }
            
    return events;
    }
    //
    @Override
    public void updateEvent(Event event) throws InvalidEventFormatException{
        em.merge(event);
    }
    //
    @Override
    public void DeleteEvent(int eventId){
        em.remove(getEvent(eventId));
    }
    @Override
   public Event checkEvent(String name){
       event=em.find(Event.class,name);
       return event;
   }
   @Override
   public Event getEvent(int eventId){
        event=em.find(Event.class, eventId);
   return event;}
   
   @Override
  public List<Event> getAllEventOfDay(Date day){
      
       events= em.createNamedQuery("Event.findByDateEvent").getResultList();
   return events;
  }
 //return list of id of all invited
  @Override
  public List<Users> splitInvited(String invited){
      int id=0;
     StringTokenizer string= new StringTokenizer(invited,";"); 

      while (string.hasMoreTokens()) {
          id=usersDao.getUserId(string.nextToken());
         result.add(usersDao.getUser(id));
            }
            
      return result;    
           
  }
}
